//
//  ViewController.m
//  myhuibao
//
//  Created by lijun on 13-2-4.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "BoxSearchViewController.h"
#import "RestaurantDetailViewController.h"

#import "SearchCell.h"
#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJson.h"
@interface BoxSearchViewController ()

@end

@implementation BoxSearchViewController
@synthesize mainTable;
//@synthesize cityId;
//@synthesize areaId;
//@synthesize diningDate;
//@synthesize diningTime;
//@synthesize boxType;
//@synthesize capacity;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    wqTable = mainTable;
    
    pageIndex=1;
    [self getSearchResult];
    }
- (void) getSearchResult{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_searchBox];
    ASIFormDataRequest *request=[ASIFormDataRequest requestWithURL:url];
    [request setPostValue:[NSString stringWithFormat:@"%d",pageIndex++] forKey:@"pageIndex"];
    [request setPostValue:[NSString stringWithFormat:@"%d",_cityId] forKey:@"cityID"];
    if(_areaId != 0)
        [request setPostValue:[NSString stringWithFormat:@"%d",_areaId] forKey:@"areaID"];
    if(_boxType != 0)
        [request setPostValue:[NSString stringWithFormat:@"%d",_boxType] forKey:@"boxTypeID"];
    if(_capacity != 0)
        [request setPostValue:[NSString stringWithFormat:@"%d",_capacity] forKey:@"boxCapacityID"];

    [request setPostValue:_diningDate forKey:@"diningDate"];
    [request setPostValue:[NSString stringWithFormat:@"%d",_diningTime] forKey:@"diningTime"];

    [request setPostValue:@"31.8421" forKey:@"latitude"];
    [request setPostValue:@"117.8421" forKey:@"longitude"];
    
    [request setDelegate: self];
    [request startAsynchronous];
    

}
//下面是两个代理函数,当数据请求成功时会调用requestFinished，请求失败时（如网络问题或服务器内部错误）会调用requestFailed
- (void)requestFinished:(ASIHTTPRequest *)request
{
    // Use when fetching text data
    NSString *jsonStr = [request responseString];
//    NSLog(@"%@",jsonStr);
    NSDictionary *dic = [jsonStr JSONValue];
    
    tableDataArray = [dic valueForKey:@"data"];
    //NSLog(@"%@", tableDataArray);
    returnCount = [tableDataArray count];
    delegate=self;
    
    [mainTable reloadData];
    // Use when fetching binary data
//    NSData *responseData = [request responseData];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
}

- (void)viewDidUnload
{
    [self setMainTable:nil];
    wqTable = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
}
//- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
//{
//    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
//    if (self) {
//        self.title=@"搜索结果";
//    }
//    return self;
//}
// customize the number of rows in the table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	int count = [tableDataArray count];
    return count+1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}
- (CGFloat)tableView:(UITableView *)tableView widthForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 320;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *CellIdentifier = @"SearchCellIdentifier";
    
        
    if([indexPath row] < ([tableDataArray count])) {
        
        SearchCell *cell = (SearchCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//        if (cell == nil) {
            NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"SearchCell" owner:nil options:nil];
            cell = [array objectAtIndex:0];
            [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
//        }
        
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];
        
        
        cell.name = [item valueForKey:@"name"];
        cell.address = [item valueForKey:@"address"] ;
        cell.distance = [item valueForKey:@"distance"] ==[NSNull null]?@"未知" : [NSString stringWithFormat:@"%d",[[item valueForKey:@"distance"] intValue]/1000];
        cell.cuisine = [item valueForKey:@"cuisine"] ==[NSNull null]?@"未知" : [item valueForKey:@"cuisine"];
        cell.discount = [item valueForKey:@"discount"] ==[NSNull null]?@"" : [NSString stringWithFormat:@"%d",[[item valueForKey:@"discount"] intValue]];
        cell.score = [item valueForKey:@"score"] == [NSNull null]? [NSNumber numberWithFloat:0] : [NSNumber numberWithFloat:[[item valueForKey:@"score"] floatValue]];
        NSString *imageName = [[tableDataArray objectAtIndex:indexPath.row] valueForKey:@"ID"];
        // [[[tableDataArray objectAtIndex:indexPath.row] valueForKey:@"image"]stringByAppendingString:@".temp"];
        if(imageName == nil || (NSNull *)imageName == [NSNull null])
        {
            cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];
            return  cell;
        }
        imageName = [NSString stringWithFormat:@"%d%@",[[[tableDataArray objectAtIndex:indexPath.row] valueForKey:@"ID"] intValue],@".temp"];//[imageName stringByAppendingString:@".temp"];
        //        NSLog(@"%@",imageName);
        NSString *imageDataPath = [NSHomeDirectory() stringByAppendingPathComponent:[@"Library/Caches/" stringByAppendingString:imageName]];
        UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfFile:imageDataPath]];
        if (image) {
            cell.imageView.image = image;
        }
        else
        {
            cell.imageView.image = [UIImage imageNamed:@"Placeholder.png"];
            //placeholder为在未加载完成加载图片时显示的默认图片
        }
        return cell;

    }else{
        
              
          UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
//              if (cell == nil)
          {
              cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                            reuseIdentifier:CellIdentifier];
              cell.selectionStyle = UITableViewCellSelectionStyleNone;
          }
          
          if(returnCount<pageSize){
              cell.textLabel.text=@"";
          }else{
              //创建loadMoreCell
              cell.textLabel.text=str_more;
          }
          cell.textLabel.textAlignment = UITextAlignmentCenter;
          cell.detailTextLabel.text=@"";
          cell.imageView.image =nil;
          return cell;

    }
    
}
-(void)cellImageDidLoad:(NSIndexPath *)indexPath image:(UIImage *)image
{
    UITableViewCell *cell = [wqTable cellForRowAtIndexPath:indexPath];
//    cell.imageView.image = image;
    cell.imageView.image = [image copy];

}

- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.row == [tableDataArray count]) {
        UITableViewCell *loadMoreCell=[tableView cellForRowAtIndexPath:indexPath];
        loadMoreCell.textLabel.text=str_loading;
//        [self performSelectorInBackground:@selector(loadMore) withObject:nil];
//        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?pageIndex=%d",url_searchList,pageIndex++]] ;
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
        [request startSynchronous];
        NSString *jsonStr = [request responseString];
        
        NSDictionary *dic = [jsonStr JSONValue];
        NSMutableArray *array = [dic valueForKey:@"data"];
        returnCount = [array count];
        [self performSelectorOnMainThread:@selector(appendTableWith:) withObject:array waitUntilDone:NO];
//        [dic release];
//        [array release];
        return;
    }else{
        RestaurantDetailViewController  *view = [[RestaurantDetailViewController alloc] initWithNibName:@"RestaurantDetailViewController" bundle:nil];
        //传递商户id参数
        NSDictionary *item = [tableDataArray objectAtIndex:indexPath.row];

        view.merchantId =[[item objectForKey:@"ID"] intValue];
        view.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:view animated:YES];
//        [view release];

    }
    //其他cell的事件
    
}
-(void) appendTableWith:(NSMutableArray *)data
{   //将loadMore中的NSMutableArray添加到原来的数据源listData中.
    for (int i=0;i<[data count];i++) {
        [tableDataArray addObject:[data objectAtIndex:i]];
    }
    NSMutableArray *insertIndexPaths = [NSMutableArray arrayWithCapacity:pageSize];
    for (int ind = 0; ind < [data count]; ind++) {
        NSIndexPath    *newPath =  [NSIndexPath indexPathForRow:[tableDataArray indexOfObject:[data objectAtIndex:ind]] inSection:0];
        [insertIndexPaths addObject:newPath];
    }
    //重新调用UITableView的方法, 来生成行.
    [self.mainTable insertRowsAtIndexPaths:insertIndexPaths withRowAnimation:UITableViewRowAnimationFade];
}
- (void)dealloc {
    [mainTable release];
    [super dealloc];
}


@end
